<template>
  <div class="init-container">
    <div class="mask-container" v-if="isMask"></div>
    <Modal
      v-model="showModal"
      draggable
      sticky
      scrollable
      :mask="true"
      mask-closable
      title="上料前操作"
      width="800"
      @on-ok="closeModal"
      @on-cancel="closeModal"
    >
      <div class="modal-content">
        <!-- 头部 -->
        <div class="header">
          <div>{{ realTimeBarCode.label }}:</div>
          <Input
            v-model="realTimeBarCode.value"
            style="width: auto;margin-left: 10px;"
            readonly
          />
        </div>

        <!-- 中部 -->
        <div class="main">
          <Row :gutter="16">
            <Col span="12">
              <div
                class="input-group"
                v-for="(item, index) in workOrders"
                :key="index"
              >
                <Input
                  v-model="item.value"
                  placeholder="请扫描或输入派工单号"
                  :suffix="scanIcon"
                  @on-blur="validateCode(item, index, 'workOrder')"
                />
                <Button type="text" @click="refreshCode(index)"
                  ><Icon type="md-refresh" class="big-icon"
                /></Button>
              </div>
            </Col>
            <Col span="12">
              <div
                class="input-group"
                v-for="(item, index) in partNums"
                :key="index"
              >
                <InputNumber
                  v-model="item.value"
                  :min="1"
                  :max="999"
                  placeholder="请输入数量"
                  @on-blur="validateCode(item, index, 'partNum')"
                />
                <Button type="error" ghost @click="removeItem(index)"
                  ><Icon class="big-icon" type="md-remove-circle"
                /></Button>
              </div>
            </Col>
          </Row>
        </div>

        <!-- 底部 -->
        <div class="footer">
          <Button
            type="primary"
            size="large"
            :disabled="!canGenerate"
            @click="generateGroup"
          >
            生成挂组 (总数: {{ totalQuantity }})
          </Button>
          <Button
            type="success"
            size="large"
            :disabled="!canComplete"
            @click="completeLoading"
          >
            上料完成
          </Button>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script lang="ts">
import { Tsrv, T_srv, ifs, ts, vue, I_cmd, T_cmd } from './config';

interface WorkOrder {
  code: string;
  btnCode: string;
  value: number | null | string;
}

@T_srv.comp
export default class beforeLoadModal extends vue {
  @T_srv.prop({ required: true, type: Boolean, default: false })
  visible!: boolean;

  /* 组件名 */
  private name: string = 'beforeLoadModal';

  /* 遮罩 */
  public isMask: boolean = false;

  private showModal: boolean = false;

  // 实时条码
  private realTimeBarCode = {
    label: '实时条码',
    code: 'my861',
    value: 'ABCD1234'
  };

  // 派工单列表
  private workOrders: WorkOrder[] = [
    { code: 'my862', value: null, btnCode: 'my3838' },
    { code: 'my863', value: null, btnCode: 'my3839' },
    { code: 'my864', value: null, btnCode: 'my3840' },
    { code: 'my865', value: null, btnCode: 'my3841' },
    { code: 'my866', value: null, btnCode: 'my3842' }
  ];

  // 零件数列表
  private partNums: WorkOrder[] = [
    { code: 'my867', value: null, btnCode: 'my3843' },
    { code: 'my868', value: null, btnCode: 'my3844' },
    { code: 'my869', value: null, btnCode: 'my3845' },
    { code: 'my870', value: null, btnCode: 'my3846' },
    { code: 'my871', value: null, btnCode: 'my3847' }
  ];

  // 扫描图标
  private scanIcon = 'wy-icon ios-scan';

  // 计算属性
  get totalQuantity(): number {
    return this.partNums.reduce((sum, item) => {
      return sum + (Number(item.value) || 0);
    }, 0);
  }

  get canGenerate(): boolean {
    let flag = true;
    this.workOrders.forEach((item, index) => {
      if (
        Tsrv.noValue(item.value) &&
        !Tsrv.noValue(this.partNums[index].value)
      ) {
        flag = false;
      } else if (
        Tsrv.noValue(this.partNums[index].value) &&
        !Tsrv.noValue(item.value)
      ) {
        flag = false;
      }
    });
    return flag;
  }

  get canComplete(): boolean {
    return this.canGenerate;
  }

  @T_srv.watch('visible')
  private onVisibleChange(value: boolean): void {
    this.showModal = value;
    this.loadData();
  }

  created() {
    this.showModal = this.visible;
  }

  mounted() {
    this.loadData();
  }

  private loadData() {
    const codes = this.workOrders
      .map(item => item.code)
      .concat(this.partNums.map(item => item.code));

    codes.push(this.realTimeBarCode.code);
    Tsrv.readPlcData(codes).then(res => {
      if (typeof res === 'boolean') return;
      this.workOrders.forEach(item => {
        item.value = res[item.code].v;
      });
      this.partNums.forEach(item => {
        item.value = res[item.code].v;
      });
      this.realTimeBarCode.value = res[this.realTimeBarCode.code].v;
    });
  }

  // 方法
  private validateCode(item: WorkOrder, index: number, type: string): void {
    // 空值校验
    if (Tsrv.noValue(item.value)) {
      return;
    }

    if (type === 'workOrder') {
      // 重复校验
      const duplicate = this.workOrders
        .filter((i, idx) => idx !== index)
        .some(i => i.value === item.value);

      if (duplicate) {
        this.$Message.error('条码重复');
        item.value = null;
        this.partNums[index].value = null;
        return;
      }
    }

    // 写入plc数据
    const data = [{ ecDetCode: item.code, value: item.value.toString() }];
    Tsrv.writePlcData(data).then(_ => {
      // 读取条码更新数据
      Tsrv.readPlcData([item.code]).then(r => {
        if (typeof r === 'boolean') return;

        type === 'workOrder'
          ? (this.workOrders[index].value = r[item.code].v)
          : (this.partNums[index].value = r[item.code].v);
      });
    });
  }

  private refreshCode(index: number): void {
    const data = [{ ecDetCode: this.workOrders[index].btnCode, value: 'true' }];
  }

  private removeItem(index: number): void {
    this.workOrders[index].value = null;
    this.partNums[index].value = null;
  }

  private generateGroup(): void {
    // const data = [{ ecDetCode: 'my855', value: 'true' }];
    const data = [{ ecDetCode: 'myTest001', value: 'true' }];
    Tsrv.writePlcData(data).then(success => {
      if (success) {
        this.$Message.success('生成挂组成功');
      }
    });
  }

  private completeLoading(): void {
    const data = [{ ecDetCode: 'my624', value: 'true' }];
    Tsrv.writePlcData(data).then(success => {
      if (success) {
        this.$Message.success('上料完成');
        this.closeModal();
      }
    });
  }

  // 关闭弹窗
  private closeModal(): void {
    this.$emit('on-close');
  }
}
</script>
<style lang="scss" scoped>
::v-deep .ivu-modal-header {
  background-color: #dcd4da;
  border-radius: 5px 5px 0 0;
}

::v-deep .ivu-modal-footer {
  background-color: #dcd4da;
  border-radius: 0 0 5px 5px;
}
.modal-content {
  padding: 20px;

  .header {
    margin-bottom: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .main {
    margin: 20px 0;

    .big-icon {
      font-size: 16px;
    }

    .input-group {
      display: flex;
      align-items: center;
      margin-bottom: 10px;

      .ivu-input-wrapper,
      .ivu-input-number {
        flex: 1;
        margin-right: 10px;
      }
    }
  }

  .footer {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;

    .ivu-btn {
      width: 48%;
    }
  }
}
</style>
